#include "SDL/SDL.h"
#include "SDL/SDL_image.h"
#include "SDL/SDL_ttf.h"
#include "state.h"
#include "constants.h"
#include "functions.h"
#include <iostream>
using namespace std;

//Globals
SDL_Surface *screen;
State *currentState;		//Current State (Obj)
GameStatesType nextState;	//Next State    (Num)
GameStatesType stateID;		//Current State (Num)

//Constants from constants.h
extern const int SCREEN_WIDTH;
extern const int SCREEN_HEIGHT;
extern const int SCREEN_BPP;
extern const int FRAMES_PER_SECOND;
SDL_Event event;

bool init_sdl();
void change_state();

int main(int argc, char* args[])
{
	int frame = 0; //This holds the current number of frames that have been animated
	//Timer fps; ToDo: Crete Timer class

	//Initialize SDL
	if(!init_sdl())
	{
		//SDL Failed to initialize
		cout << "SDL Failed to initialize!" << endl;
		return 1;
	}

	//Main Loop
	currentState = new TitleScreen;
	stateID = STATE_INTRO;
	while(stateID!=STATE_EXIT)
	{
		//TODO Start FPS timer

		//Handle Events
		currentState->handle_events();

		//Do Logic
		currentState->logic();

		//Do Rendering
		currentState->render();

		//Change State
		change_state();

		if(SDL_Flip(screen) == -1)
		{
			return 1;
		}
		frame++;

		/*
		//If we want to cap the frame rate
		if((cap == true) && (fps.get_ticks() < 1000 / FRAMES_PER_SECOND))
		{
			//Sleep the remaining frame time
			SDL_Delay((1000 / FRAMES_PER_SECOND) - fps.get_ticks());
		}*/

	}

	return 0;
}

bool init_sdl()
{
	/*Initialize all SDL subsystems
	 *
	 */
	if(SDL_Init(SDL_INIT_EVERYTHING) == -1)
	{
		return false;
	}

	//Set up the screen
	screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE);

	//If there was an error in setting up the screen
	if(screen == NULL)
	{
		return false;
	}

	//Set the window caption
	SDL_WM_SetCaption("SDL TD", NULL);
	return true;
}

void change_state()
{
	//Attempts to change the game state
	if(nextState != STATE_NULL)
	{
		if(nextState != STATE_EXIT)
		{
			try
			{
				delete currentState;
			}
			catch(...)
			{
				cout << "Could not delete Current State!" << endl << flush;
			}
		}

		switch(nextState)
		{
			case STATE_INTRO:
				nextState = STATE_NULL;
				cout << "Loading Intro..." << endl << flush;
				currentState = new TitleScreen();
				break;
			case STATE_PLAYING:
				nextState = STATE_NULL;
				//TODO: currentState = new Playing();
				break;
			default:
				//Do Nothing, this is here to shut the compiler up
				break;
		}

		//Set the new stateID
		stateID = nextState;
	}
}
